﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.PrintService;
using CoreShop.Services;
using CoreShop.Services.Services.Report;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using static CoreShop.Library.GlobalEnumVars;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace CoreShop.App
{
    public partial class frmPrintSchemeDetailInfo : UIForm
    {
        private corecmsprintbilltype printbilltypeModel;
        private corecmsprintscheme printscheme;
        private corecmsprintschemedetail chemedetail = new corecmsprintschemedetail();
        private corecmsprintbilltemplate billtemplate = new corecmsprintbilltemplate();

        public frmPrintSchemeDetailInfo(corecmsprintbilltype _billType, corecmsprintscheme _printscheme)
        {
            printscheme = _printscheme;
            printbilltypeModel = _billType;
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void frmPrintSchemeDetailInfo_Load(object sender, System.EventArgs e)
        {
            BindComboBoxData();
            chemedetail = new corecmsprintschemedetailServices().SelectById(printbilltypeModel.printSchemeId, printbilltypeModel.id);
            if (chemedetail == null)
            {
                chemedetail = new corecmsprintschemedetail();
                chemedetail.selectedFlag = true;
                chemedetail.foodPackPrintType = (int)GlobalEnumVars.foodPackPrintType.PackAndFood;
                if ((printbilltypeModel.id == (int)GlobalEnumVars.PrintbillType.PrePayment)
                    || (printbilltypeModel.id == (int)GlobalEnumVars.PrintbillType.Settlement))
                {
                    chemedetail.foodPackPrintType = (int)GlobalEnumVars.foodPackPrintType.PackOnly;
                } 
            }
            ControlsDataBinding.DataBind(chemedetail, this, DataSourceUpdateMode.OnPropertyChanged);
            //打印类型
            corecmsprintbilltype printbilltype = new corecmsprintbilltypeServices().SelectByType(printbilltypeModel.id);
            if (printbilltype != null) billtypeId.SelectedValue = printbilltype.id;
            
            //打印方案
            //printscheme = new corecmsprintschemeServices().SelectById(billType.printSchemeId);
            if (printscheme != null) printSchemeId.SelectedValue = printscheme.id;

            //打印格式模板
            billtemplate = new corecmsprintbilltemplateServices().SelectById(printbilltypeModel.templateId);
            if (billtemplate != null)
            {
                templateId.SelectedValue = billtemplate.id;
                //打印方式
                foodPrintType.SelectedValue = billtemplate.foodPrintType;
            }

            //商品展示顺序
            foodSort.SelectedValue = chemedetail.foodSort;
            chbSelectedFlag.Checked = chemedetail.selectedFlag;
            //foodSort.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.foodSort>(billType.foodSort.ObjToInt(0));

            this.printCount.Value = CommFunc.ConvertToInt32(chemedetail.printCount);

            foodPackPrintType.SelectedValue = chemedetail.foodPackPrintType;

            if (printbilltypeModel.id > (int)GlobalEnumVars.PrintbillType.FoodList)
                pnlFoodPack.Visible = false;

            if (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command)
            {
                btnPrintPreview.Visible = false;
            } 
            else
            {
                //自定义预结帐单和小票打印，可以修改商品打印方式
                if ((printbilltypeModel.id == (int)GlobalEnumVars.PrintbillType.Settlement)
                    || (printbilltypeModel.id == (int)GlobalEnumVars.PrintbillType.PrePayment))
                this.foodPrintType.Enabled = true;
            }
            if (chemedetail.billtypeId != (int)GlobalEnumVars.PrintbillType.Label)
            {
                this.foodPrintType.SelectedValue = (int)GlobalEnumVars.foodPrintType.Order;
                this.foodPrintType.Enabled = false;
            }                
        }

        public void BindTemplateData(int selectIndex)
        {
            #region 加载打印格式模板
            this.templateId.DataSource = null;
            this.templateId.Items.Clear();
            List<corecmsprintbilltemplate> template = new corecmsprintbilltemplateServices().AsQueryable().Where(p=>p.billtypeId == printbilltypeModel.id).ToList();
            this.templateId.DataSource = template;
            this.templateId.DisplayMember = "name";
            this.templateId.ValueMember = "id";
            if (template.Count > selectIndex) this.templateId.SelectedIndex = selectIndex;
            #endregion
        }

        public void BindComboBoxData()
        {
            BindTemplateData(0);

            #region 加载打印方案
            this.printSchemeId.Items.Clear();
            List<corecmsprintscheme> chemeList = new corecmsprintschemeServices().QueryAsync(0);
            this.printSchemeId.DataSource = chemeList;
            this.printSchemeId.DisplayMember = "printerName";
            this.printSchemeId.ValueMember = "id";
            if (chemeList.Count > 0) this.printSchemeId.SelectedIndex = 0;
            #endregion

            #region 加载打印类型
            this.billtypeId.Items.Clear();
            List<corecmsprintbilltype> typeList = new corecmsprintbilltypeServices().QueryAsync(0);
            this.billtypeId.DataSource = typeList;
            this.billtypeId.DisplayMember = "name";
            this.billtypeId.ValueMember = "id";
            if (typeList.Count > 0) this.billtypeId.SelectedIndex = 0;
            #endregion

            #region 加载商品打印方式
            this.foodPrintType.Items.Clear(); //printbilltypeModel
            //if (printbilltypeModel.tagId == (int)GlobalEnumVars.PrintbillTypeTag.Account)
            var printList = EnumHelper.EnumToList<GlobalEnumVars.foodPrintType>();
            
            //if (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Drive)
            if (printscheme.printerType == (int)GlobalEnumVars.printerType.PosBill) 
            {
                //printList = EnumHelper.EnumToList<GlobalEnumVars.foodPrintType>()
                //    .Where(p => p.value ==(int)GlobalEnumVars.foodPrintType.Order || p.value == (int)GlobalEnumVars.foodPrintType.Summary).ToList();
                printList = EnumHelper.EnumToList<GlobalEnumVars.foodPrintType>().ToList();
            }
            this.foodPrintType.DataSource = printList;
            this.foodPrintType.DisplayMember = "description";
            this.foodPrintType.ValueMember = "value";
            if (printList.Count > 0) this.foodPrintType.SelectedIndex = 0;
            #endregion

            #region 加载商品展示顺序
            this.foodSort.Items.Clear();
            var foodSortList = EnumHelper.EnumToList<GlobalEnumVars.foodSort>();
            this.foodSort.DataSource = foodSortList;
            this.foodSort.DisplayMember = "description";
            this.foodSort.ValueMember = "value";
            this.foodSort.SelectedIndex = 1;
            #endregion

            #region 加载套餐打印方式
            this.foodPackPrintType.Items.Clear();
            var printTypeList = EnumHelper.EnumToList<GlobalEnumVars.foodPackPrintType>();
            this.foodPackPrintType.DataSource = printTypeList;
            this.foodPackPrintType.DisplayMember = "description";
            this.foodPackPrintType.ValueMember = "value";
            this.foodPackPrintType.SelectedIndex = 0;
            #endregion
        }

        private void btnOk_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (!CheckData()) return;
                if (chemedetail == null) chemedetail = new corecmsprintschemedetail();
                chemedetail.printSchemeId = CommFunc.ConvertToInt32(printSchemeId.SelectedValue);
                chemedetail.templateId = CommFunc.ConvertToInt32(templateId.SelectedValue);
                chemedetail.billtypeId = CommFunc.ConvertToInt32(billtypeId.SelectedValue);
                chemedetail.printCount = printCount.Value;
                chemedetail.foodSort = CommFunc.ConvertToInt32(foodSort.SelectedValue);
                chemedetail.selectedFlag = chbSelectedFlag.Checked;
                chemedetail.foodPackPrintType = CommFunc.ConvertToInt32(foodPackPrintType.SelectedValue);
                if (chemedetail.id > 0)
                {
                    DoEdit();
                }
                else
                {
                    DoCreate();
                }
                //SetControlClear();
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void DoEdit()
        {
            try
            {
                if (new corecmsprintschemedetailServices().InsertOrUpdate(chemedetail))
                {
                    if ((printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Drive) && this.foodPrintType.Enabled)
                    {
                        //自定义打印，可以修改商品打印方式
                        var templateServers = new corecmsprintbilltemplateServices();
                        var billtemplateModel = templateServers.GetById(billtemplate.id);//要重新打开，修改保存时已保存
                        billtemplateModel.foodPrintType = CommFunc.ConvertToInt32(foodPrintType.SelectedValue);
                        templateServers.UpdateAsync(billtemplateModel);
                    }

                    ShowSuccessTip("保存成功");
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    UIMessageBox.Show("保存失败", "提示", UIStyle.Red, UIMessageBoxButtons.OK);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void DoCreate()
        {
            try
            {
                if (new corecmsprintschemedetailServices().InsertAsync(chemedetail))
                {
                    ShowSuccessTip("保存成功");
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    UIMessageBox.Show("保存失败", "提示", UIStyle.Red, UIMessageBoxButtons.OK);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        private bool CheckData()
        {
            try
            {
                if (printSchemeId.Text == null || printSchemeId.Text == "")
                {
                    UIMessageBox.Show("请输入打印方案", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (billtypeId.Text == null || billtypeId.Text == "")
                {
                    UIMessageBox.Show("请输入打印类型", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (foodPrintType.Text == null || foodPrintType.Text == "")
                {
                    UIMessageBox.Show("请输入打印方式", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (foodSort.Text == null || foodSort.Text == "")
                {
                    UIMessageBox.Show("请输入商品展示顺序", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if (printCount.Value <= 0)
                {
                    UIMessageBox.Show("请输入打印份数", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
            }
            catch (Exception)
            {
                throw;
            }
            return true;
        }

        private void btnAddBill_Click(object sender, EventArgs e)
        {
            PrinterUnits.ShowPrintBillSet(printscheme, null, 0, CommFunc.ConvertToInt32(billtypeId.SelectedValue),0);
            int selectIndex = this.templateId.SelectedIndex;
            if (selectIndex < 0) selectIndex = 0;
            BindTemplateData(selectIndex);
        }

        private void btnEditBill_Click(object sender, EventArgs e)
        {
            int sTemplateId = CommFunc.ConvertToInt32(templateId.SelectedValue);
            corecmsprintbilltemplate printbilltemplate = new corecmsprintbilltemplateServices().SelectById(sTemplateId);
            if (printbilltemplate == null)
            {
                UIMessageBox.Show("模板不存在，无法修改。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            if (printscheme == null)
            {
                UIMessageBox.Show("打印不存在，无法修改。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            if (chemedetail == null) chemedetail = new corecmsprintschemedetail();
            int sbilltypeId = CommFunc.ConvertToInt32(billtypeId.SelectedValue);
            int sfoodPrintType = CommFunc.ConvertToInt32(foodPrintType.SelectedValue);
            if (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command)
            {
                PrinterUnits.ShowPrintBillSet(printscheme, printbilltemplate, 1, sbilltypeId, sfoodPrintType);
            }
            else {
                new ReportServices().SetDesignReport(printbilltemplate); 
            }
            
            int selectIndex = this.templateId.SelectedIndex;
            BindTemplateData(selectIndex);
        }

        private void templateId_SelectedValueChanged(object sender, EventArgs e)
        {
            int sTemplateId = this.templateId.SelectedIndex;
            corecmsprintbilltemplate printbilltemplate = new corecmsprintbilltemplateServices().SelectById(sTemplateId);
            if (printbilltemplate != null)
            {
                foodPrintType.SelectedValue = printbilltemplate.foodPrintType;
            }
        }

        private void btnPrintPreview_Click(object sender, EventArgs e)
        {
            int sTemplateId = CommFunc.ConvertToInt32(templateId.SelectedValue);
            corecmsprintbilltemplate printbilltemplate = new corecmsprintbilltemplateServices().SelectById(sTemplateId);
            if ((printbilltemplate == null) || string.IsNullOrEmpty(printbilltemplate.reportFile))
            {
                UIMessageBox.Show("模板不存在，无法修改。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            if (printscheme == null)
            {
                UIMessageBox.Show("打印机不存在，无法修改。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            switch (printbilltypeModel.id)
            {
                case (int)GlobalEnumVars.PrintbillType.Settlement:
                    PrintPreviewSettlement(printbilltemplate);
                    break;
                case (int)GlobalEnumVars.PrintbillType.PrePayment:
                    PrintPreviewPrePayment(printbilltemplate);
                    break;
                case (int)GlobalEnumVars.PrintbillType.FoodList:
                    PrintPreviewFoodList(printbilltemplate);
                    break;
                case (int)GlobalEnumVars.PrintbillType.ClassBill:
                    var classData = new corecmsfoodorderclassServices().GetClassData(AppConstVars.classId);
                    new PrintServices().SetPrintClassBill(classData, true);
                    break;
                case (int)GlobalEnumVars.PrintbillType.UserDeposit:
                    PrintPreviewFoodList(printbilltemplate);
                    break;
                case (int)GlobalEnumVars.PrintbillType.Label:
                    var orderMaster = new corecmsfoodordermasterServices().QueryFirst();
                    if (orderMaster == null)
                    {
                        UIMessageBox.Show("没有可打印的数据，请结算一个单作为打印实例。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                        return;
                    }
                    new PrintServices().SetPrintLabel(orderMaster,true); //打印标签纸
                    break;
                default: 
                    break;
            }

        }
        private void PrintPreviewSettlement(corecmsprintbilltemplate printbilltemplate)
        {
            var orderMaster = new corecmsfoodordermasterServices().QueryFirst();
            if (orderMaster == null)
            {
                UIMessageBox.Show("没有可打印的数据，请结算一个单作为打印实例。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            new ReportServices().SetPrintSettlement(orderMaster, printbilltemplate, true);
        }

        private void PrintPreviewFoodList(corecmsprintbilltemplate billtemplate)
        {
            var orderingMaster = new corecmsfoodorderingmasterServices().QueryFirst();
            if (orderingMaster == null)
            {
                UIMessageBox.Show("没有可打印的数据，请下单一个桌号为打印实例。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            var orderings = new corecmsfoodorderingServices().AsQueryable().Where(p=>p.orderId ==  orderingMaster.orderId).ToList();
            string strDetail = JsonConvert.SerializeObject(orderings);
            var printtaskdetail = JsonConvert.DeserializeObject<List<corecmsprinttaskdetail>>(strDetail);

            new ReportServices().SetPrinOrdering(printtaskdetail, billtemplate, orderingMaster, true);
        }

        private void PrintPreviewPrePayment(corecmsprintbilltemplate billtemplate)
        {
            var orderingMaster = new corecmsfoodorderingmasterServices().QueryFirst();
            if (orderingMaster == null)
            {
                UIMessageBox.Show("没有可打印的数据，请下单一个桌号为打印实例。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            var orderings = new corecmsfoodorderingServices().AsQueryable().Where(p => p.orderId == orderingMaster.orderId).ToList();
            string strDetail = JsonConvert.SerializeObject(orderings);
            var printtaskdetail = JsonConvert.DeserializeObject<List<corecmsprinttaskdetail>>(strDetail);

            new ReportServices().SetPrintPrePayment(orderingMaster, billtemplate,true);
        }
    }
}